import axios, { AxiosHeaders, AxiosResponse } from 'axios';
import router from '../router';
import { useTokenStore } from '../store/UseTokenStore';
import { ElMessage } from 'element-plus';
import CommonConstant from '../common/SystemConstant';
import { Result } from '../domain/entity/Result';

const tokenManager = useTokenStore()

const config = {
  baseURL: "http://127.0.0.1:9420",
  timeout: 100000,
  headers: {
    Authorization: tokenManager.bearerToken
  }
}

const instance = axios.create(config);



// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  // console.log("111", config);
  // config!.headers['Authorization'] = tokenManager.bearerToken;
  // let authorizationHeader: AxiosHeaders = new AxiosHeaders();
  // authorizationHeader.set("Authorization", tokenManager.bearerToken);
  let headers = config.headers as AxiosHeaders;
  headers.set("Authorization", tokenManager.bearerToken);

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function(response:AxiosResponse<Result<any>, any>) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  let resultEntity:Result<any> = response.data;
  // let finalData = data.data;
  // console.log(response);
  
  // 当权限验证不通过的时候给出提示
  if (resultEntity.code === 401) {
    ElMessage.warning("登录超时,重新登录");
    tokenManager.removeToken()
    router.push(CommonConstant.loginRoutePath)
  }
  if (resultEntity.code != 0) {
    ElMessage.error(resultEntity.msg);
    throw new Error(resultEntity.msg);

  }
  return response;
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // console.log(error);
  if (error.code === "ERR_NETWORK") {
    ElMessage.error("网络异常");
  } else if (error?.response?.status === 401) {
    ElMessage.warning("登录超时,重新登录");
    tokenManager.removeToken();
    router.push(CommonConstant.loginRoutePath)
  } else if (error?.response?.status === 403) {
    ElMessage.warning("用户无权限");
  } else if (error?.response?.status === 400 && !!error?.response?.data?.msg) {
    ElMessage.error(error?.response?.data?.msg);
  } else if (error?.response?.status === 500 && !!error?.response?.data?.msg) {
    ElMessage.error(error?.response?.data?.msg);
  } else {
    ElMessage.error(error.message);
  }

  // 对响应错误做点什么
  return Promise.reject(error);
});


export default instance;